<?php
namespace app\index\controller\wanlshop;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

use addons\wanlshop\library\WanlChat\WanlChat;
use app\common\controller\Wanlshop;
use addons\wanlshop\library\WanlSdk\Ehund; //快递100订阅

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    /**
     * Order模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Order;
        $kuaidi = new \app\index\model\wanlshop\Kuaidi;
		$this->wanlchat = new WanlChat();
        $this->view->assign("kuaidiList", $kuaidi->field('name,code')->select());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statesList", $this->model->getStatesList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['id','username','nickname','avatar']);
				$row->pay = model('app\index\model\wanlshop\Pay')
					->where(['order_id' => $row['id'], 'type' => 'goods'])
					->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
					->find();

            }
            $list = collection($list)->toArray();
			
			
            $result = array("total" => $total, "rows" => $list);
            $this->model->where("admin_read",1)->where('shop_id',$this->shop->id)->update(['admin_read'=>2]);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function timi_msg()
    {
        $count = $this->model->where("admin_read",1)->where('shop_id',$this->shop->id)->count();
        if($count > 0){
            $data['num'] = $count;
            $data['url'] = url('wanlshop/order').'?ref=addtabs';
            $this->success("有新订单消息", "", $data);
        }
    }
    /**
     * 导出
     */
    public function export()
    {
//        if ($this->request->isPost()) {
        set_time_limit(0);
        ini_set ('memory_limit', '2048M');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField'))
        {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $ids = $this->request->post('ids'); //获取数据的所有id
        //查询数据
        $wheres = [];
        if ($ids != 'all' && !is_null($ids)) {
            $wheres['id'] = ['in', $ids];
        }
        $total_ids = $this->model
            ->where($where)
            ->where($wheres)
            ->order($sort, $order)
            ->column('id');
        $total=model('app\api\model\wanlshop\OrderGoods')->whereIn('order_id',$total_ids)->count();

//            $total = 1;
        $list = $this->model
            ->where($where)
            ->where($wheres)
            ->order($sort, $order)
//            ->limit($offset, $limit)
//                ->limit(1)
            ->select();
        if(!is_array($list) && !is_null($list)){
            $list=$list->toArray();
        }
        $new_data=[];
        foreach ($list as $row) {
//                $row->getRelation('user')->visible(['username','nickname']);
//                $row->getRelation('shop')->visible(['shopname']);
            $row->pay = model('app\admin\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->find();
            $row->user = model('app\admin\model\User')
                ->field('id, nickname, mobile')
                ->where(['id' => $row['user_id']])
                ->find();
            $row->address = model('app\api\model\wanlshop\OrderAddress')
                ->where(['order_id' => $row['id']])
                ->order('isaddress desc')
                ->field('name,mobile,address')
                ->find();
            $order_goods_data=model('app\api\model\wanlshop\OrderGoods')->where('order_id',$row['id'])->select();
            if(!is_array($order_goods_data) && !is_null($order_goods_data)){
                $order_goods_data=$order_goods_data->toArray();
            }
            foreach ($order_goods_data as $k=>$v){
                $this_data=[
                    'order_data'=>$row,
                    'goods_data'=>$v,
                ];
                $new_data[]=$this_data;
            }


        }
        $list = collection($list)->toArray();
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('订单列表');  //设置当前sheet的标题
        $objSheet->getDefaultColumnDimension()->setWidth(30);

        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('O')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('P')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('Q')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('R')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('S')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('T')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('U')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('V')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('W')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('X')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('Y')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('Z')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AA')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AB')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AC')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AD')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AE')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AF')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AG')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AH')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AI')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('AJ')->setAutoSize(true);


        $objSheet->setCellValue('A1', '订单ID')
            ->setCellValue('B1', '订单编号')
            ->setCellValue('C1', '交易号')
            ->setCellValue('D1', '支付方式')
            ->setCellValue('E1', '优惠金额')
            ->setCellValue('F1', '商品小计')
            ->setCellValue('G1', '运费')
            ->setCellValue('H1', '应收款')
            ->setCellValue('I1', '已退款金额')
            ->setCellValue('J1', '剩余金额')
            ->setCellValue('K1', '交易状态')
            ->setCellValue('L1', '下单时间')
            ->setCellValue('M1', '付款时间')
            ->setCellValue('N1', '发货时间')
            ->setCellValue('O1', '完成时间')
            ->setCellValue('P1', '快递公司')
            ->setCellValue('Q1', '快递单号')
            ->setCellValue('R1', '订单备注')
            ->setCellValue('S1', '会员ID')
            ->setCellValue('T1', '会员昵称')
            ->setCellValue('U1', '会员手机号')
            ->setCellValue('V1', '交易订单号')
            ->setCellValue('W1', '商品名称')
            ->setCellValue('X1', '商品编码')
            ->setCellValue('Y1', '购买规格')
            ->setCellValue('Z1', '数量')
            ->setCellValue('AA1', '单价')
            ->setCellValue('AB1', '总价')
            ->setCellValue('AC1', '优惠')
            ->setCellValue('AD1', '实际支付')
            ->setCellValue('AE1', '运费')
            ->setCellValue('AF1', '配送方式')
            ->setCellValue('AG1', '收货人姓名')
            ->setCellValue('AH1', '收货人手机号')
            ->setCellValue('AI1', '收货地址')

        ;
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        //$i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
// 创建一个样式数组
        $styleArray = [
            'font' => [
                'bold' => true, // 加粗
                'size' => 16, // 字体大小
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, // 水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, // 垂直居中
            ],
        ];

// 应用样式到第一行
        $objSheet->getStyle('A1:AJ1')->applyFromArray($styleArray);
        $cache_order_id=0;
        $cell_num_start=0;
        $cell_num_end=0;
        for ($i = 2; $i <= $total+1; $i++) {
            $objSheet->setCellValue('A' . $i, $new_data[$i-2]['order_data']['id'])
                ->setCellValue('B' . $i, '编号：'.$new_data[$i-2]['order_data']['order_no'])
                ->setCellValue('C' . $i, $new_data[$i-2]['order_data']['pay']['pay_no'])
                ->setCellValue('D' . $i, $new_data[$i-2]['order_data']['pay']['pay_type_text'])
                ->setCellValue('E' . $i, $new_data[$i-2]['order_data']['pay']['coupon_price'])
                ->setCellValue('F' . $i, $new_data[$i-2]['order_data']['pay']['order_price'])
                ->setCellValue('G' . $i, $new_data[$i-2]['order_data']['pay']['freight_price'])
                ->setCellValue('H' . $i, $new_data[$i-2]['order_data']['pay']['order_price'])
                ->setCellValue('I' . $i, $new_data[$i-2]['order_data']['pay']['refund_price'])
                ->setCellValue('J' . $i, $new_data[$i-2]['order_data']['pay']['order_price']-$new_data[$i-2]['order_data']['pay']['refund_price'])
                ->setCellValue('K' . $i, $new_data[$i-2]['order_data']['state_text'])
                ->setCellValue('L' . $i, $new_data[$i-2]['order_data']['createtime_text'])
                ->setCellValue('M' . $i, $new_data[$i-2]['order_data']['paymenttime_text'])
                ->setCellValue('N' . $i, $new_data[$i-2]['order_data']['delivertime_text'])
                ->setCellValue('O' . $i, $new_data[$i-2]['order_data']['dealtime_text'])
                ->setCellValue('P' . $i, $new_data[$i-2]['order_data']['express_name'])
                ->setCellValue('Q' . $i, $new_data[$i-2]['order_data']['express_no'])
                ->setCellValue('R' . $i, $new_data[$i-2]['order_data']['remarks'])
                ->setCellValue('S' . $i, $new_data[$i-2]['order_data']['user']['id'])
                ->setCellValue('T' . $i, $new_data[$i-2]['order_data']['user']['nickname'])
                ->setCellValue('U' . $i, $new_data[$i-2]['order_data']['user']['mobile'])
                ->setCellValue('V' . $i, $new_data[$i-2]['order_data']['pay']['trade_no'])
                ->setCellValue('W' . $i, $new_data[$i-2]['goods_data']['title'])
                ->setCellValue('X' . $i, $new_data[$i-2]['goods_data']['goods_sku_sn'])
                ->setCellValue('Y' . $i, $new_data[$i-2]['goods_data']['difference'])
                ->setCellValue('Z' . $i, $new_data[$i-2]['goods_data']['number'])
                ->setCellValue('AA' . $i, $new_data[$i-2]['goods_data']['price'])
                ->setCellValue('AB' . $i, $new_data[$i-2]['goods_data']['price']*$new_data[$i-2]['goods_data']['number'])
                ->setCellValue('AC' . $i, $new_data[$i-2]['goods_data']['discount_price'])
                ->setCellValue('AD' . $i, $new_data[$i-2]['goods_data']['actual_payment'])
                ->setCellValue('AE' . $i, $new_data[$i-2]['goods_data']['freight_price'])
                ->setCellValue('AF' . $i, $new_data[$i-2]['order_data']['express_name'])
                ->setCellValue('AG' . $i, $new_data[$i-2]['order_data']['address']['name'])
                ->setCellValue('AH' . $i, $new_data[$i-2]['order_data']['address']['mobile'])
                ->setCellValue('AI' . $i, $new_data[$i-2]['order_data']['address']['address'])
            ;

            if($new_data[$i-2]['order_data']['id']!=$cache_order_id){

                $cache_order_id=$new_data[$i-2]['order_data']['id'];
                $cell_num_start=$i;
                $cell_num_end=0;
            }else{
                $cell_num_end=$i;
                if($cell_num_end!=0 && $cell_num_start!=0 && $cache_order_id!=0){
                    //处理合并-检测是否最后一行   是则合并
                    $deal=false;
                    if(!isset($new_data[$i-1])){
                        $deal=true;
                    }else{
                        if($new_data[$i-1]['order_data']['id']!=$new_data[$i-2]['order_data']['id']){
                            $deal=true;
                        }
                    }
                    if($deal){
                        $objSheet->mergeCells('A'.$cell_num_start.':A'.$cell_num_end);
                        $objSheet->mergeCells('B'.$cell_num_start.':B'.$cell_num_end);
                        $objSheet->mergeCells('C'.$cell_num_start.':C'.$cell_num_end);
                        $objSheet->mergeCells('D'.$cell_num_start.':D'.$cell_num_end);
                        $objSheet->mergeCells('E'.$cell_num_start.':E'.$cell_num_end);
                        $objSheet->mergeCells('F'.$cell_num_start.':F'.$cell_num_end);
                        $objSheet->mergeCells('G'.$cell_num_start.':G'.$cell_num_end);
                        $objSheet->mergeCells('H'.$cell_num_start.':H'.$cell_num_end);
                        $objSheet->mergeCells('I'.$cell_num_start.':I'.$cell_num_end);
                        $objSheet->mergeCells('J'.$cell_num_start.':J'.$cell_num_end);
                        $objSheet->mergeCells('K'.$cell_num_start.':K'.$cell_num_end);
                        $objSheet->mergeCells('L'.$cell_num_start.':L'.$cell_num_end);
                        $objSheet->mergeCells('M'.$cell_num_start.':M'.$cell_num_end);
                        $objSheet->mergeCells('N'.$cell_num_start.':N'.$cell_num_end);
                        $objSheet->mergeCells('O'.$cell_num_start.':O'.$cell_num_end);
                        $objSheet->mergeCells('P'.$cell_num_start.':P'.$cell_num_end);
                        $objSheet->mergeCells('Q'.$cell_num_start.':Q'.$cell_num_end);
                        $objSheet->mergeCells('R'.$cell_num_start.':R'.$cell_num_end);
                        $objSheet->mergeCells('S'.$cell_num_start.':S'.$cell_num_end);
                        $objSheet->mergeCells('T'.$cell_num_start.':T'.$cell_num_end);
                        $objSheet->mergeCells('U'.$cell_num_start.':U'.$cell_num_end);
                        $objSheet->mergeCells('V'.$cell_num_start.':V'.$cell_num_end);
                        $objSheet->mergeCells('AF'.$cell_num_start.':AF'.$cell_num_end);
                        $objSheet->mergeCells('AG'.$cell_num_start.':AG'.$cell_num_end);
                        $objSheet->mergeCells('AH'.$cell_num_start.':AH'.$cell_num_end);
                        $objSheet->mergeCells('AI'.$cell_num_start.':AI'.$cell_num_end);
                    }
                }
            }

        }



        /*--------------下面是设置其他信息------------------*/
//            $title = date("Ymd-公摊详情");
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
//            header('Cache-Control: max-age=0');
//            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
//            $objWriter->save('php://output');
//            return;

        $outputFileName = date("YmdHis") . '-导出订单.xlsx';
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;

//        }
    }
    public function export_old()
    {
//        if ($this->request->isPost()) {
        set_time_limit(0);
        ini_set ('memory_limit', '2048M');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField'))
        {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $ids = $this->request->post('ids'); //获取数据的所有id
        //查询数据
        $wheres = [];
        if ($ids != 'all') {
            $wheres['id'] = ['in', $ids];
        }

        $total = $this->model
            ->where($where)
            ->where($wheres)
            ->order($sort, $order)
            ->count();
//            $total = 1;
        $list = $this->model
            ->where($where)
            ->where($wheres)
            ->order($sort, $order)
//            ->limit($offset, $limit)
//                ->limit(1)
            ->select();

        foreach ($list as $row) {
//                $row->getRelation('user')->visible(['username','nickname']);
//                $row->getRelation('shop')->visible(['shopname']);
            $row->pay = model('app\admin\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->find();
            $row->user = model('app\admin\model\User')
                ->field('id, nickname, mobile')
                ->where(['id' => $row['user_id']])
                ->find();
            $row->address = model('app\api\model\wanlshop\OrderAddress')
                ->where(['order_id' => $row['id']])
                ->order('isaddress desc')
                ->field('name,mobile,address')
                ->find();
        }
        $list = collection($list)->toArray();
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('订单列表');  //设置当前sheet的标题
        $objSheet->getDefaultColumnDimension()->setWidth(30);

        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('O')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('P')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('Q')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('R')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('S')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('T')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('U')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('V')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('W')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('X')->setAutoSize(true);



        $objSheet->setCellValue('A1', '订单ID')
            ->setCellValue('B1', '订单编号')
            ->setCellValue('C1', '支付单号')
            ->setCellValue('D1', '支付方式')
            ->setCellValue('E1', '优惠金额')
            ->setCellValue('F1', '商品小计')
            ->setCellValue('G1', '运费')
            ->setCellValue('H1', '应收款')
            ->setCellValue('I1', '已退款金额')
            ->setCellValue('J1', '剩余金额')
            ->setCellValue('K1', '订单状态')
//                ->setCellValue('L1', '售后状态')
            ->setCellValue('L1', '下单时间')
            ->setCellValue('M1', '付款时间')
            ->setCellValue('N1', '发货时间')
            ->setCellValue('O1', '完成时间')
            ->setCellValue('P1', '快递公司')
            ->setCellValue('Q1', '快递单号')
            ->setCellValue('R1', '订单备注')
            ->setCellValue('S1', '会员ID')
            ->setCellValue('T1', '会员昵称')
            ->setCellValue('U1', '会员手机号')
            ->setCellValue('V1', '收货人姓名')
            ->setCellValue('W1', '收货人手机号')
            ->setCellValue('X1', '收货地址');
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        //$i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
// 创建一个样式数组
        $styleArray = [
            'font' => [
                'bold' => true, // 加粗
                'size' => 16, // 字体大小
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, // 水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, // 垂直居中
            ],
        ];

// 应用样式到第一行
        $objSheet->getStyle('A1:R1')->applyFromArray($styleArray);
        for ($i = 2; $i <= $total+1; $i++) {
            $objSheet->setCellValue('A' . $i, $list[$i-2]['id'])
                ->setCellValue('B' . $i, '编号：'.$list[$i-2]['order_no'])
                ->setCellValue('C' . $i, $list[$i-2]['pay']['pay_no'])
                ->setCellValue('D' . $i, $list[$i-2]['pay']['pay_type_text'])
                ->setCellValue('E' . $i, $list[$i-2]['pay']['coupon_price'])
                ->setCellValue('F' . $i, $list[$i-2]['pay']['order_price'])
                ->setCellValue('G' . $i, $list[$i-2]['pay']['freight_price'])
                ->setCellValue('H' . $i, $list[$i-2]['pay']['order_price'])
                ->setCellValue('I' . $i, $list[$i-2]['pay']['refund_price'])
                ->setCellValue('J' . $i, $list[$i-2]['pay']['order_price']-$list[$i-2]['pay']['refund_price'])
                ->setCellValue('K' . $i, $list[$i-2]['state_text'])
//                    ->setCellValue('L' . $i, $new_data[$i-2]['pay']['order_price'])
                ->setCellValue('L' . $i, $list[$i-2]['createtime_text'])
                ->setCellValue('M' . $i, $list[$i-2]['paymenttime_text'])
                ->setCellValue('N' . $i, $list[$i-2]['delivertime_text'])
                ->setCellValue('O' . $i, $list[$i-2]['dealtime_text'])
                ->setCellValue('P' . $i, $list[$i-2]['express_name'])
                ->setCellValue('Q' . $i, $list[$i-2]['express_no'])
                ->setCellValue('R' . $i, $list[$i-2]['remarks'])
                ->setCellValue('S' . $i, $list[$i-2]['user']['id'])
                ->setCellValue('T' . $i, $list[$i-2]['user']['nickname'])
                ->setCellValue('U' . $i, $list[$i-2]['user']['mobile'])
                ->setCellValue('V' . $i, $list[$i-2]['address']['name'])
                ->setCellValue('W' . $i, $list[$i-2]['address']['mobile'])
                ->setCellValue('X' . $i, $list[$i-2]['address']['address']);
//                    ->setCellValue('I' . $i, date('Y-m-d H:i:s',$sql[$i-2]['id']));
        }


        /*--------------下面是设置其他信息------------------*/
//            $title = date("Ymd-公摊详情");
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
//            header('Cache-Control: max-age=0');
//            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
//            $objWriter->save('php://output');
//            return;

        $outputFileName = date("YmdHis") . '-导出订单.xlsx';
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;

//        }
    }
    
    /**
     * 详情
     */
    public function detail($id = null, $order_no = null)
    {
    	$where = $order_no ? ['order_no' => $order_no] : ['id' => $id];
        $row = $this->model
    		->where($where)
    		->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断权限
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        $row['address'] = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
			
		$row['pay'] = model('app\index\model\wanlshop\Pay')
			->where(['order_id' => $row['id'], 'type' => 'goods'])
			->find();
			
		// 查询快递状态
		switch ($row['state']) {
			case 1:
				$express = [
					'context' => '付款后，即可将宝贝发出',
					'status' => '尚未付款',
					'time' => date('Y-m-d H:i:s', $row['createtime'])
				];
				break;
			case 2:
				$express = [
					'context' => '商家正在处理订单',
					'status' => '已付款',
					'time' => date('Y-m-d H:i:s', $row['paymenttime'])
				];
				break;
			default: // 获取物流
				$eData = model('app\api\model\wanlshop\KuaidiSub')
					->where(['express_no' => $row['express_no']])
					->find();
				// 获取数据 兼容PHP7.4	1.1.5升级
				$ybData = json_decode($eData['data'], true);
				if(!empty($ybData)){
					// 运单状态 1.0.6升级
					$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
					$status = $statusText[0];
					if(in_array('status', $ybData[0])){
						$status = $ybData[0]['status'];
					}else{
						if($eData['ischeck'] === 1){
							$status = $statusText[3];
						}else{
							$status = $statusText[$eData['state']];
						}
					}
					$express = [
						'status' => $status,
						'context' => $ybData[0]['context'],
						'time' => $ybData[0]['time'],
					];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹正在等待快递小哥揽收~',
						'time' => date('Y-m-d H:i:s', $row['delivertime'])
					];
				}
		}
		$this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	/**
	 * 快递查询
	 */
	public function relative($id = null)
	{
		$row = $this->model->get($id);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		// 判断权限
		if ($row['shop_id'] != $this->shop->id) {
		    $this->error(__('You have no permission'));
		}
		$data = model('app\index\model\wanlshop\KuaidiSub')
			->where(['express_no' => $row['express_no']])
			->find();
		$list = [];
		$week = array("0"=>"星期日","1"=>"星期一","2"=>"星期二","3"=>"星期三","4"=>"星期四","5"=>"星期五","6"=>"星期六");
		if($data){
			// 兼容PHP7.4	1.1.6升级
			$ybData = json_decode($data['data'], true);
			if(!empty($ybData)){
				foreach($ybData as $vo){
					$list[] = [
						'time' => strtotime($vo['time']),
						'status' => in_array('status', $vo) ? $vo['status'] : '在途', // 1.0.6升级
						'context' => $vo['context'],
						'week' => $week[date('w', strtotime($vo['time']))]
					];
				}
			}
		}
		$this->view->assign("week", $week);
		$this->view->assign("list", $list);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
    
    /**
     * 打印发货单 1.1.2升级
     */
    public function invoice($ids = null)
    {
        $list = $this->model->all($ids);
        if (!$list) {
            $this->error(__('No Results were found'));
        }
        foreach ($list as $row) {
            // 判断权限
            if ($row['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $row['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
    		$row['pay'] = model('app\index\model\wanlshop\Pay')
    			->where(['order_id' => $row['id'], 'type' => 'goods'])
    			->field('id,number,actual_payment,order_price,freight_price,discount_price,price')
    			->find();
        }
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }
    
    /**
     * 发货 & 批量发货
     */
    public function delivery($ids = null)
    {
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		$data = [];
		$lists = [];
		$mobile = [];
        foreach ($row as $vo) {
			if ($vo['shop_id'] != $this->shop->id) {
			    $this->error(__('You have no permission'));
			}
			$address = model('app\index\model\wanlshop\OrderAddress')
			    ->where(['order_id' => $vo['id'], 'shop_id' => $this->shop->id])
			    ->order('isaddress desc')
			    ->field('id,name,mobile,address,address_name')
			    ->find();
			$vo['address'] = $address;
			if ($vo['state'] == 2) {
			    $lists[] = $vo;
			} else {
			    $data[] = $vo;
			}
			$mobile[$vo['id']] = $address['mobile'];
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if (!array_key_exists("order", $request['row'])) {
                $this->success(__('没有发现可以发货订单~'));
            }
			if(!$this->wanlchat->isWsStart()){
				$this->error('平台未启动IM即时通讯服务，暂时不可以发货');
			}
            $config = get_addon_config('wanlshop');
            $ehund = new Ehund($config['kuaidi']['secretKey'], $config['ini']['appurl'].$config['kuaidi']['callbackUrl']);
            $order = [];
			$express = [];
			foreach ($request['row']['order']['id'] as $key => $id) {
                $express_no = $request['row']['order']['express_no'][$key];
                $express_name = $request['row']['express_name'];
                $order[] = [
                    'id' => $id,
                    'express_name' => $express_name,
                    'express_no' => $express_no,
                    'delivertime' => time(),
                    'state' => 3
                ];
				// 1.0.5升级 查询是否存在,如果存在绕过快递100订阅
				$is_express_no = model('app\index\model\wanlshop\KuaidiSub')->where(['express_no' => $express_no])->count();
                // 订阅快递查询
                if ($config['kuaidi']['secretKey'] && $is_express_no == 0) {
                    $returncode = $ehund->subScribe($express_name, $express_no, $mobile[$id]);
                    if ($returncode['returnCode'] != 200) {
                        $this->error('快递订阅接口异常-'.$returncode['message']);
                    }
                    $express[] = [
                        'sign' => $ehund->sign($express_no),
                        'express_no' => $express_no,
                        'returncode' => $returncode['returnCode'],
                        'message' => $returncode['message']
                    ];
                }
				// 推送消息
				$this->pushOrder($id,'已发货');
            }
			// 使用事务 1.1.2升级
			$result = false;
			Db::startTrans();
			try {
			  	$result = $this->model->saveAll($order);
			  	// 写入快递订阅列表
			  	if ($express) model('app\index\model\wanlshop\KuaidiSub')->saveAll($express);
				Db::commit();
			} catch (PDOException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (Exception $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			}
			// 判断是否支付成功
			if($result){
				$this->success();
			}else{
				$this->error('网络异常，发货失败');
			}
        }
        $this->view->assign("lists", $lists); //可以发货
        $this->view->assign("data", $data);
        return $this->view->fetch();
    }
    
    /**
     * 评论管理
     */
    public function comment()
    {
        return $this->view->fetch('wanlshop/comment/index');
    }
	
	/**
	 * 订单推送消息（方法内使用）
	 * 
	 * @param string order_id 订单ID
	 * @param string state 状态
	 */
	private function pushOrder($order_id = 0, $state = '已发货')
	{
		$order = $this->model->get($order_id);
		$orderGoods = model('app\index\model\wanlshop\OrderGoods')
			->where(['order_id' => $order_id])
			->select();
		$msgData = [];
		foreach ($orderGoods as $goods) {
			$msg = [
				'user_id' => $order['user_id'], // 推送目标用户
				'shop_id' => $this->shop->id, 
				'title' => '您的订单'.$state, // 推送标题
				'image' => $goods['image'], // 推送图片
				'content' => '您购买的商品 '.(mb_strlen($goods['title'],'utf8') >= 25 ? mb_substr($goods['title'],0,25,'utf-8').'...' : $goods['title']).' '.$state, 
				'type' => 'order',  // 推送类型
				'modules' => 'order',  // 模块类型
				'modules_id' => $order_id,  // 模块ID
				'come' => '订单'.$order['order_no'] // 来自
			];
			$msgData[] = $msg;
			$this->wanlchat->send($order['user_id'], $msg);
		}
		$notice = model('app\index\model\wanlshop\Notice')->saveAll($msgData);
	}
}
